package com.lanzhou.yuanfen.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * 导出Excel工具
 *
 * @author Administrator
 */
public class ExcelExportUtil {

    /**
     * 用于导出配置数据
     *
     * @param workBook    工作溥
     * @param data        表数据
     * @param excelHeader 表头对应的 Key :标题
     * @param title       数据
     */
    public static void setExcel(Workbook workBook,
                                List<Map<String, String>> data,
                                LinkedHashMap<String, String> excelHeader,
                                String title) {
        Sheet sheet = workBook.createSheet("ZQ-数据导出模板");
        String[] keys = new String[excelHeader.size()];
        String[] headers = new String[excelHeader.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : excelHeader.entrySet()) {
            keys[i] = entry.getKey();
            headers[i] = entry.getValue();
            i++;
        }
        // 设置表头
        setExcelHead(workBook, sheet, headers, title);
        // 配置数据
        setExcelBody(workBook, sheet, data, keys);
    }


    /**
     * 填充表数据
     *
     * @param workBook 工作浦
     * @param sheet    第几页
     * @param data     数据
     * @param keys     属性名称
     */
    private static void setExcelBody(Workbook workBook, Sheet sheet, List<Map<String, String>> data, String[] keys) {
        int columnNumber = 2;
        int size = data.size();
        CellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        cellStyle.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
        Font font = workBook.createFont();
        font.setFontHeightInPoints((short) 14);
        cellStyle.setFont(font);
        for (int i = 0; i < size; i++) {
            Row row1 = sheet.createRow(columnNumber + i);
            for (int j = 0; j < keys.length; j++) {
                Cell cell = row1.createCell(j);
                cell.setCellValue(data.get(i).getOrDefault(keys[j], ""));
                cell.setCellStyle(cellStyle);
            }
        }
    }


    /**
     * 设置表头
     *
     * @param workBook 工作蒲
     * @param sheet    工作页面
     * @param headers  表头信息
     * @param title    标题
     */
    private static void setExcelHead(Workbook workBook, Sheet sheet, String[] headers, String title) {
        // 创建第一个表头
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue(title);
        // 设置表头居中样式
        CellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        cellStyle.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
        Font font = workBook.createFont();
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));
        Row row1 = sheet.createRow(1);
        for (int i = 0; i < headers.length; i++) {
            Cell cell1 = row1.createCell(i);
            cell1.setCellValue(headers[i]);
            cell1.setCellStyle(cellStyle);
            sheet.setColumnWidth(i, 8000);
        }
    }


    /**
     * 导出操作
     *
     * @param response 响应体
     * @param workBook 工作蒲
     * @param fileName 文件名
     */
    public static void export(HttpServletResponse response, Workbook workBook, String fileName) {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Pragma", "No-Cache");
        response.setHeader("Cache-Control", "No-Cache");
        response.setDateHeader("Expires", 0);
        // response.setContentType("application/x-download");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //客户端的弹出对话框，对应的文件名 (中文字符需要转一下编码)
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            workBook.write(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
